package so.ifl.commons.tools.pinter.impl;

import java.io.ByteArrayOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.DoradoSystemUtils;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.SystemUtil;
import so.ifl.commons.tools.except.SessionTimeOutException;
import so.ifl.commons.tools.pinter.Iprinter;
import so.ifl.servcie.ExamBookingDetailService;
import so.ifl.servcie.ExamBookingService;
import so.ifl.vo.AccountVo;
import so.ifl.vo.ExamBookingDetailVo;
import so.ifl.vo.ExamBookingVo;

/**
 *create by aaron.lu
 *create at 2012-2-24 上午12:38:18
 *<mailto: atyuan.lu@gmail.com>
 **/
public class Subject3Printer implements Iprinter {
	
	Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	private String EXAM_BOOKING_DETAIL_LIST = "list";
	private String EXAM_BOOKING = "exambooking";
	private String SCHOOL_NAME;

	

	@Override
	public void print(Map<String, Object> data, HttpServletResponse response, HttpServletRequest request) throws Exception {
		logger_.debug("param:" + data);
		
		List<ExamBookingDetailVo> list = (List<ExamBookingDetailVo>)data.get(EXAM_BOOKING_DETAIL_LIST);
		ExamBookingVo exambooking = (ExamBookingVo)data.get(EXAM_BOOKING);
		
		if (null == exambooking) {
			//非空判断
			throw new Exception("nullpoint of exam_booking info...");
		}
		
		
		int count = list.size();// 总记录数
		int pageCount = 8;// 每页记录数
		int page = 0;// 总共页数
		/** 主要控制总共的页数 */
		if (count >= pageCount && count % pageCount == 0) {//如果恰好整数
			page = count / pageCount;
		} else {//非整数
			page = count / pageCount + 1;
		}
		
		ByteArrayOutputStream baos[] = new ByteArrayOutputStream[page];// 用于存储每页生成PDF流
		
		String servletPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath();
		String model_path = servletPath + "/templates/subject2_3.pdf";
		PdfReader reader = new PdfReader(model_path);
		
		BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		
		int list_current = 0;//队列中被输出到pdf的序号
		
		for (int i = 0; i < page; i++) {
			baos[i] = new ByteArrayOutputStream();
			PdfStamper pdfStamper = new PdfStamper(reader, baos[i]);
			
			AcroFields form = pdfStamper.getAcroFields(); 
			form.addSubstitutionFont(baseFontChinese);
			
			if (count % pageCount != 0 && i == page - 1) {//最后一页
				logger_.debug("====pageCount+" + pageCount + "=====");
				pageCount = count % pageCount;
			}
			
			form.setField("title", "中山市汽车驾驶员报考科目三及成绩登记表");
			
			Date times=exambooking.getExamBookingDate();
			Calendar ca = Calendar.getInstance();   
			ca.setTime(times);    
			form.setField("examBookingDate_y", ""+ca.get(Calendar.YEAR));
			form.setField("examBookingDate_m", "" + (ca.get(Calendar.MONTH) + 1));
			form.setField("examBookingDate_d", ""+ca.get(Calendar.DAY_OF_MONTH));
			form.setField("carnumber", exambooking.getExamCarNumber());
			form.setField("trainerLicenseNumber", exambooking.getTrainerLicenseNumber());			
			form.setField("testPlay", exambooking.getTestPlay());
			form.setField("cartype", exambooking.getExamCarType());
			form.setField("carmodel", exambooking.getExamCarModel());
			form.setField("examtrainer", exambooking.getExamTrainer());
			form.setField("trainerphone", exambooking.getTrainerPhone());
			
			AccountVo accountVo = DoradoSystemUtils.getCurrentUser(request);
			if (null == accountVo) {
				throw new SessionTimeOutException("登录超时");
			}
			
			form.setField("accountOwner", exambooking.getExamCreateUser());
			form.setField("accountTel", exambooking.getExamContact());
			
			Date now = new Date();
			Calendar ca_ = Calendar.getInstance();   
			ca_.setTime(now);    
			form.setField("now_y", ""+ca_.get(Calendar.YEAR));
			form.setField("now_m", ""+(ca_.get(Calendar.MONTH) + 1));
			form.setField("now_d", ""+ca_.get(Calendar.DAY_OF_MONTH));
			
			
			if (null != list && list.size() > 0 ) {
				for (int j = 0; j < pageCount; j++) {
					if (j < list.size()) {
						ExamBookingDetailVo vo = list.get(list_current++);
						form.setField("name" + j, vo.getStudentName());
						form.setField("studentCertificateNumber" + j, vo.getStudentCertificateNumber());
						form.setField("studentFileId" + j, vo.getStudentSerialNum());//2012.10.08更新流水号
						form.setField("getCertTime" + j, null != vo.getGetCertTime()?DateUtil.YMD_SDF_SIMPLE_POINT.format(vo.getGetCertTime()):"");
						Integer testType = vo.getTestType();
						if(null != testType && testType.intValue() == 1){
							form.setField("f" + j, "√");
						}else if (null != testType && testType.intValue() == 2) {
							form.setField("s" + j, "√");
						}
						form.setField("officeName", SCHOOL_NAME);
					}//超过记录总数					
				}
			}
			pdfStamper.setFormFlattening(true); // 千万不漏了这句啊, */
			pdfStamper.close();
			
		}//end of for
		
		ServletOutputStream out = response.getOutputStream();
		
		response.setContentType("application/pdf");
		
		for (int i = 0; i < baos.length; i++) {
			logger_.info(baos[i].size() + " bytes has write to out..");
			
			baos[i].writeTo(out);
			out.flush();						
			
			baos[i].close();
		}
		out.close();

	}

	@Override
	public Map<String, Object> getData(HttpServletRequest request)throws Exception {
		ServletContext servletContext = request.getSession().getServletContext();		
		ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		
		Map<String, Object> data = new HashMap<String, Object>();

		ExamBookingDetailService exambookingdetailService = (ExamBookingDetailService)appctx.getBean("exambookingdetailService");
		ExamBookingService exambookingService = (ExamBookingService)appctx.getBean("exambookingService");
		
		String exam_booking_id_ = request.getParameter("exam_booking_id_");
		String temp = request.getParameter("school");
		SCHOOL_NAME = SystemUtil.getCompany(temp);
		
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		if (StringHelper.isNotEmpty(exam_booking_id_)) {
			params.put("exam_booking_id_", exam_booking_id_);
		 	
			List<ExamBookingDetailVo> list = exambookingdetailService.queryExamBookingDetailWithParamAndPagination(params, 0, 10000);
			List<ExamBookingVo> listVo = exambookingService.queryExamBookingWithParamAndPagination(params, 0, 1);
			
			data.put(EXAM_BOOKING_DETAIL_LIST, list);
			if (null != list && listVo.size() > 0) {
				data.put(EXAM_BOOKING, listVo.get(0));
			}			
		}
		
		return data;
	}

}
